#include "glwidget.h"

#include <QDebug>


GLWidget::GLWidget(QWidget *parent) :
    QGLWidget(parent)
{
    m_canvas_ptr = NULL;
    this->setMaximumSize(600,600);
    this->setMinimumSize(600,600);
}

void GLWidget::initializeGL()
{
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glViewport(0,0,this->width(),this->height());
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    gluPerspective(45.0,(float)this->width()/(float)this->height(),0.01,100.0);
    gluLookAt(0.0,0.0,-1.0,0.0,0.0,-1.0,0.0,1.0,0.0);
    glClearColor(0.4,0.4,0.4,1.0);

    glEnable(GL_TEXTURE_2D);
    glGenTextures(1, &m_texture_id);
    glBindTexture(GL_TEXTURE_2D,m_texture_id);

    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_REPEAT);

    QImage *img = new QImage(256,256,QImage::Format_RGB32);

    for(int i = 0; i < 256; i++){
        for(int j = 0; j < 256; j++){
            img->setPixel(i,j,QColor(0,0,0).rgb());
        }
    }
    img->save("dummy.png");

    m_gl_texture = QGLWidget::convertToGLFormat(*img);
    glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,m_gl_texture.width(),m_gl_texture.height(),0,GL_RGBA, GL_UNSIGNED_BYTE, m_gl_texture.bits());
    delete img;
}

void GLWidget::set_canvas(Canvas *canvas_ptr)
{
    if(canvas_ptr != NULL){
        m_canvas_ptr = canvas_ptr;
        update_texture();
    }
}

void GLWidget::paintGL()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glBegin(GL_QUADS);
    glTexCoord2f(0.0,0.0);
    glVertex3f(-1.0,-1.0,-3.0);
    glTexCoord2f(1.0,0.0);
    glVertex3f(1.0,-1.0,-3.0);
    glTexCoord2f(1.0,1.0);
    glVertex3f(1.0,1.0,-3.0);
    glTexCoord2f(0.0,1.0);
    glVertex3f(-1.0,1.0,-3.0);
    glEnd();
}

void GLWidget::resizeGL(int w, int h)
{
    int max = glm::max(w,h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glViewport(0,0,600,600);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    gluPerspective(45.0,(float)600/(float)600,0.01,100.0);
    gluLookAt(0.0,0.0,-0.6,0.0,0.0,-1.0,0.0,1.0,0.0);
    this->update();
}

void GLWidget::update_texture()
{
    m_canvas_ptr->get_image()->save("update_img.png");
    m_gl_texture = QGLWidget::convertToGLFormat(*(m_canvas_ptr->get_image()));
    m_gl_texture.save("conv_update.png");
    glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,m_gl_texture.width(),m_gl_texture.height(),0,GL_RGBA, GL_UNSIGNED_BYTE, m_gl_texture.bits());
    this->update();
}
